package com.lczyfz.istep.modules.mobile.entity;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.utils.IdGen;

import java.io.*;

/**
 * Created by DH on 2017/3/21.
 */
public class Code {
    // 文件的目录名
//    private String dirName = "mobile";
    private String dirName = "";
    public void encode()throws Exception {
        //获取密钥文件
        String code="abcde";
        byte[] passwd=code.getBytes();
        //获取原视频文件
        BufferedInputStream bisOld = new BufferedInputStream(new FileInputStream(new File("D:\\1234.mp4")));
        //输出加密后的流文件
        BufferedOutputStream bosNew = new BufferedOutputStream(new FileOutputStream(new File("D:\\12345678.mp4")));
        //写入密钥
        bosNew.write(passwd);

        byte[] buffer=new byte[1024];
        int len=0;
        //加密文件
        while((len=bisOld.read(buffer))>0){
            bosNew.write(buffer, 0, len);
        }

        bosNew.flush();
        bosNew.close();
        bisOld.close();

    }
    /**
     * 解密
     * @throws Exception
     */
    public void  decode(MobileFile mobileFile)throws Exception {
        //获取密钥文件
//        String code="abcde";

        //为了保存名称的唯一性，使用uuid
        String name = IdGen.uuid();
        String urlLocal=mobileFile.getUrlLocal();
        String urlDecrypt= Global.USERFILES_BASE_URL+this.dirName + "/" + name + "."+mobileFile.getFormat();

        //本地保存路径
//        String urlDecryptLocal = Global.getUserfilesBaseDir().replace("/","")+ "userfiles\\" + this.dirName + "\\" + name + "."+mobileFile.getFormat();

        String urlDecryptLocal = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + this.dirName + "/" + name + "."+mobileFile.getFormat();


        mobileFile.setUrlDecrypt(urlDecrypt);
        mobileFile.setUrlDecryptLocal(urlDecryptLocal);

        byte[] passwd=mobileFile.getCode().getBytes();
        //获取加密文件
        BufferedInputStream bisOld = new BufferedInputStream(new FileInputStream(new File(urlLocal)));
        System.out.println("----urlLocal----" + urlLocal);

        System.out.println("----urlDecryptLocal----" + urlDecryptLocal);


        //输出解密后流文件

        BufferedOutputStream bosNew = new BufferedOutputStream(new FileOutputStream(new File(urlDecryptLocal)));
        //获取密钥
        bisOld.read(passwd);
        passwd=null;

        byte[] buffer=new byte[1024];
        int len=0;

        while((len=bisOld.read(buffer))>0){
            bosNew.write(buffer, 0, len);
        }

        bosNew.flush();
        bosNew.close();

        bisOld.close();

    }





}